package de.hwrberlin.remo.export.xpand;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.emf.mwe.core.WorkflowEngine;
import org.eclipse.emf.mwe.core.issues.IssuesImpl;
import org.eclipse.emf.mwe.core.issues.MWEDiagnostic;
import org.eclipse.emf.mwe.core.monitor.NullProgressMonitor;

import de.hwrberlin.remo.export.ModelExporter;

public abstract class XpandExporter implements ModelExporter {

	protected void exportModel(URL workflowFile, String template, 
			String modelFilePath, String outputFolderPath) {
		
		String workflowFilePath = "";
		try {
			workflowFilePath = FileLocator.toFileURL(workflowFile).toString();
		} catch (IOException e) {
			System.out.println(e.getMessage());
			return;
		}
		
		// Build model file path
		modelFilePath = "file:" + modelFilePath;
		modelFilePath = modelFilePath.replace("\\", "/");
		modelFilePath = modelFilePath.replace(" ", "%20");

		// Provide required workflow properties.
		Map<String, String> properties = new HashMap<String, String>();
		properties.put("model", modelFilePath);
		properties.put("src-gen", outputFolderPath);
		properties.put("template", template);
		
		// Run the generator workflow
		ClassLoader before = Thread.currentThread().getContextClassLoader();
		
		try {
			WorkflowEngine engine = new WorkflowEngine();
			engine.prepare(workflowFilePath, new NullProgressMonitor(), properties);
			
			IssuesImpl issues = new IssuesImpl();
			engine.executeWorkflow(new HashMap<String, String>(), issues);
			
			for (MWEDiagnostic i : issues.getErrors()) {
			                System.out.println(i.getMessage());
			            }
			for (MWEDiagnostic i : issues.getWarnings()) {
			                System.out.println(i.getMessage());
			            }
			
		} finally { 
			Thread.currentThread().setContextClassLoader(before);
		}
	}
	
	protected String getFileName(String completeFilePath) {
		String[] split = completeFilePath.split("\\" + String.valueOf(File.separatorChar));
		int count = split.length;
		
		return split[count - 1];
	}
	
	protected String getFolderPath(String completeFilePath) {
		String[] split = completeFilePath.split("\\" + String.valueOf(File.separatorChar));
		int count = split.length;
		
		StringBuilder pathBuilder = new StringBuilder();
		for(int i = 0; i < (count - 1); i++) {
			pathBuilder.append(split[i] + File.separator);
		}
		
		return pathBuilder.toString();	
	}
}